from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic

from django.contrib.auth.models import User
from django_common.models import ModelWithDate

class CommentManager(models.Manager):
    def add_comment(self, user, object, comment, parent = None):
        object_content_type = ContentType.objects.get_for_model(object.__class__)
        new_comment = self.model(content = comment, 
                                 content_type = object_content_type, 
                                 object_id = object.id, 
                                 user = user,
                                 parent = parent)
        new_comment.save()
        return new_comment
    
class Comment(ModelWithDate):
    content = models.TextField()
    
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey()
    user = models.ForeignKey(User)
    parent = models.ForeignKey('self', related_name = 'child_comments', null = True, blank = True)
    
    objects = CommentManager()

class ModelWithComments(models.Model):
    class Meta:
        abstract = True
    
    def associate_comments(self):
        model_content_type = ContentType.objects.get_for_model(self.__class__)
        comments = Comment.objects.filter(content_type = model_content_type, object_id = self.id).order_by('-date_created')
        return comments
    
    comments = associate_comments